package com.bicon.botu.mall.component.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.mall.component.mapper.HotSearchMapper;
import com.bicon.botu.mall.component.service.IHistorySearchService;
import com.bicon.botu.mall.component.service.IHotSearchService;
import com.bicon.botu.mall.component.common.SearchConstants;
import com.bicon.botu.mall.component.entity.HotSearch;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 热搜 服务实现类
 *
 * @author 张凡
 * @date 2017/7/19 下午 14:49
 */
@Service
@Transactional

public class HotSearchServiceImpl extends ServiceImpl<HotSearchMapper, HotSearch> implements IHotSearchService {
    @Autowired
    RedisHandler redisHandler;
    @Autowired
    IHistorySearchService iHistorySearchService;

    /**
     * 新增热词
     *
     * @param type     模块类型：全局-all,商城-mall,医疗-medical（其他待定）
     * @param hotWord  热词
     * @param showFlag 显示开关：0显示，1不显示
     * @param num      已存在的个数
     * @return
     */
    @Override
    public BaseResult insert(String type, String hotWord, String showFlag, int num) {
        HotSearch hotSearch = new HotSearch();
        hotSearch.setHotWord(hotWord);
        hotSearch.setType(type);
        hotSearch.setSort(++num);
        hotSearch.setShowFlag(showFlag);
        hotSearch.preInsert();
        boolean result = hotSearch.insert();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
        }
        //保存到redis上
        this.initHotSearchToRedis(type);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 删除热词
     *
     * @param type   模块类型：全局-all,商城-mall,医疗-medical（其他待定）
     * @param idJson 热词Id集合
     * @return
     */
    @Override
    public BaseResult delete(String type, String idJson) {
        ArrayList<String> idList = JSONObject.parseObject(idJson, ArrayList.class);
        for (int i = 0; i < idList.size(); i++) {
            HotSearch hotSearch = new HotSearch().selectById(idList.get(i));
            if (null == hotSearch) {
                return new BaseResult(Constants.RESPONSE_CODE_602, Constants.RESPONSE_MESSAGE_602);
            }
            hotSearch.setLogicDelete(Constants.DEL_LOGIC_DELETE);
            hotSearch.preUpdate();
            boolean result = hotSearch.updateById();
            if (!result) {
                return new BaseResult(Constants.RESPONSE_CODE_500, Constants.RESPONSE_MESSAGE_500);
            }
        }
        //保存到redis上
        this.initHotSearchToRedis(type);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 修改热词
     *
     * @param id       热词id
     * @param hotWord  热词
     * @param showFlag 显示开关：0显示，1不显示
     * @return
     */
    @Override
    public BaseResult update(String id, String hotWord, String showFlag) {
        HotSearch hotSearch = new HotSearch().selectById(id);
        if (hotWord != null) {
            hotSearch.setHotWord(hotWord);
        }
        if (showFlag != null) {
            hotSearch.setShowFlag(showFlag);
        }
        hotSearch.preUpdate();
        boolean result = hotSearch.updateById();
        if (!result) {
            return new BaseResult(Constants.RESPONSE_CODE_600, Constants.RESPONSE_MESSAGE_600);
        }
        //保存到redis上
        this.initHotSearchToRedis(hotSearch.getType());
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 初始化所有热词到redis
     *
     * @param type 模块类型：全局-all,商城-mall,医疗-medical（其他待定）
     * @return
     */
    @Override
    public BaseResult initHotSearchToRedis(String type) {
        //清除缓存
        redisHandler.getGlobalRedisTemplate().remove(SearchConstants.HOT_SEARCH_KEY, type);
        //只初始化系统设置的热词到redis即可
        //查询出所有正常的热搜
        List<HotSearch> hotSearchList = new HotSearch().selectList(new EntityWrapper<HotSearch>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("show_flag", SearchConstants.IS_SHOW_YES)
                .eq("type", type)
                .orderBy("sort", false));
        List<String> stringList = new ArrayList<>();
        for (HotSearch hotSearch : hotSearchList) {
            stringList.add(hotSearch.getHotWord());
        }
        //保存到redis上
        redisHandler.getGlobalRedisTemplate().cacheList(SearchConstants.HOT_SEARCH_KEY, type, stringList);
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200);
    }

    /**
     * 获取全部热搜
     *
     * @param type 模块类型：全局-all,商城-mall,医疗-medical（其他待定）
     * @return
     */
    @Override
    public List<String> getHotSearchDetailFromRedis(String type) {
        //从redis上获取全部热词
        List<String> list = redisHandler.getGlobalRedisTemplate().getList(SearchConstants.HOT_SEARCH_KEY, type);
        if (list.size() > 0) {
            if (list.size() < 5) {
                //从搜索记录获取
                List<String> hotWords = iHistorySearchService.mostSearchedWords(type, 5 - list.size());
                list.addAll(hotWords);
                //热词设置的可能和系统获取的重复需去重
                list = new ArrayList<>(new LinkedHashSet<>(list));
            }
        } else {
            list = new ArrayList<>();
            //从搜索记录获取
            List<String> hotWords = iHistorySearchService.mostSearchedWords(type, 5);
            list.addAll(hotWords);
        }
        return list;
    }
}
